﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EIS_desktop
{
    public partial class PayRoll : Form
    {
        #region fields
            private string _month,_name;
            public static double _balance;
             private int _year, _id;
             private bool IsLoading;
        #endregion

             #region properties
      /// <summary>
        /// Name of Employee
        /// </summary>
        public string EmployeeName
        {
            get { return _name; }
        }
 /// <summary>
        /// Id of Employee from Employee table
        /// </summary>
        public int EmployeeId
        {
            get { return _id; }
        }
 /// <summary>
        /// Month selected
        /// </summary>
        public string Month
        {
            get { return _month; }
        }

           /// <summary>
        /// Year selected
        /// </summary>
        public int Year
        {
            get{return _year;}
        }

public double WithHeldBalanceForward
        {
            get
            {
                try
                {
                    string datestr = "1-" + Month + "-" + Year.ToString();
                    System.Data.SqlClient.SqlConnection sqlcon = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
                    System.Data.SqlClient.SqlCommand sqlcmd = new System.Data.SqlClient.SqlCommand("select count(*) from PayRoll where Empid = " + EmployeeId, sqlcon);

                    sqlcon.Open();
                    int count = sqlcmd.ExecuteNonQuery();
                    sqlcon.Close();

                    if (count > 0)
                    {
                        sqlcmd = new System.Data.SqlClient.SqlCommand
                           ("Select BalanceWithHeldAmount from PayRoll where EmpId= " + EmployeeId +
                           " and PayPeriod = dateadd(m,-1,'" + datestr + "')", sqlcon);
                        sqlcon.Open();
                        _balance = Convert.ToDouble(sqlcmd.ExecuteScalar());
                        sqlcon.Close();
                    }
                    else
                    {
                        sqlcmd = new System.Data.SqlClient.SqlCommand("select intialbalance from BalanceIntialize where empId = " + EmployeeId, sqlcon);
                        sqlcon.Open();
                        _balance  =Convert.ToDouble(sqlcmd.ExecuteScalar());
                        sqlcon.Close();
                       
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                return _balance;
            }
        }
   #endregion

        #region constructors
 public PayRoll()
        {
            InitializeComponent();
        }
 /// <summary>
        /// pass old balances to the form
        /// </summary>
        /// <param name="month">Month</param>
        /// <param name="year">Year</param>
        /// <param name="name">Name</param>
        /// <param name="balance">Balance</param>
        public PayRoll(string month,int year,int empid,string name)
        {  
            _name = name;
            _id=empid;
            _month = month;
            _year = year;
            InitializeComponent();
                  }
#endregion

        #region Methods
        public void AddToDeductions(double totalexp)
        {
            txtDeductions.Text = totalexp.ToString();
        }
        public void AddToBalanceForward(double totalbalance)
        {
            txtWithHeldBalForw.Text = totalbalance.ToString();
        }
     private void  GetPayRollData()
        {
            IsLoading = true;
            string datestr = "1-" + Month + "-" + Year.ToString();
            System.Data.SqlClient.SqlConnection sqlcon = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
            System.Data.SqlClient.SqlCommand sqlcmd = new System.Data.SqlClient.SqlCommand
                ("Select * from PayRoll where EmpId= " + EmployeeId +
                " and PayPeriod = '" + datestr + "'", sqlcon);
            System.Data.SqlClient.SqlDataAdapter sqladp = new System.Data.SqlClient.SqlDataAdapter(sqlcmd);

            DataTable dt = new DataTable();
            sqladp.Fill(dt);
            if (dt.Rows.Count <= 0)
            {
                IsLoading = false;
                return;
                
            }
            DataRow dr = dt.Rows[0];
            cbPercentage.Text = dr["Percentage"].ToString();
            txtClientRate.Text = dr["ClientRate"].ToString();
            txtActualRate.Text = dr["ActualRate"].ToString();
            txtPaidRate.Text = dr["PaidRate"].ToString();
            txtDifference.Text = dr["difference"].ToString();
            txtHrsWorkedCurMon.Text = dr["HoursWorkedCurrentMonth"].ToString();
            txtHrsPaidFromWithHold.Text = dr["HoursPaidWithHold"].ToString();
            txtTotalHrsPaid.Text = dr["TotalHoursPaid"].ToString();
            txtCurMonWithHeldAmount.Text = dr["CurrentMonthWithHoldAmount"].ToString();
           // txtWithHeldBalForw.Text = dr["WithHoldBalanceForward"].ToString();
            txtSalFromWithHeld.Text = dr["SalaryFromWithHold"].ToString();
            txtPerDiemWithHeld.Text = dr["PerDiem_otherPayWithHeld"].ToString();
            txtBalWithHeld.Text = dr["BalanceWithHeldAmount"].ToString();
            txtFilingFeeDeduc.Text = dr["FilingFeeDeduction"].ToString();
            txtOtherAdjus.Text = dr["OtherAdjustment"].ToString();
            txtTotalPayRoll.Text = dr["Total"].ToString();
           rbRequireWHYes.Checked = (dr["RequireWithHodling"].ToString().ToLower() == "yes") ? true :false;
           rbRequireWHNo.Checked = (dr["RequireWithHodling"].ToString().ToLower() == "no") ? true : false;
           IsLoading = false;
        }
     private void CalPayTotalRoll( )
     {
         txtTotalPayRoll.Text = (Convert.ToDouble(txtBalWithHeld.Text) + Convert.ToDouble(txtOtherAdjus.Text)
             - Convert.ToDouble(txtDeductions.Text)).ToString();
     }

     private void BalanceWithHeld( )
     {
         txtBalWithHeld.Text = (Convert.ToDouble(txtCurMonWithHeldAmount.Text) + Convert.ToDouble(txtWithHeldBalForw.Text) -
               (Convert.ToDouble(txtSalFromWithHeld.Text) + Convert.ToDouble(txtPerDiemWithHeld.Text))).ToString();
     }
     private void CalculateAll( )
     {
         try
            {
                if (IsLoading) return;
                try
                {
                    txtActualRate.Text = (Convert.ToInt32(cbPercentage.Text) * Convert.ToDouble(txtClientRate.Text) / 100).ToString();
                    txtDifference.Text = (Convert.ToDouble(txtActualRate.Text) - Convert.ToDouble(txtPaidRate.Text)).ToString();
                }
                catch { }
                txtTotalHrsPaid.Text = (Convert.ToInt32(txtHrsWorkedCurMon.Text) + Convert.ToInt32(txtHrsPaidFromWithHold.Text)).ToString();
             txtCurMonWithHeldAmount.Text = (Convert.ToDouble(txtDifference.Text) * Convert.ToInt32(txtHrsWorkedCurMon.Text)).ToString();
             txtSalFromWithHeld.Text = (Convert.ToDouble(txtPaidRate.Text) * Convert.ToInt32(txtHrsPaidFromWithHold.Text)).ToString();
             txtBalWithHeld.Text = (Convert.ToDouble(txtCurMonWithHeldAmount.Text) + Convert.ToDouble(txtWithHeldBalForw.Text) -
              (Convert.ToDouble(txtSalFromWithHeld.Text) + Convert.ToDouble(txtPerDiemWithHeld.Text))).ToString();
             txtTotalPayRoll.Text = (Convert.ToDouble(txtBalWithHeld.Text) + Convert.ToDouble(txtOtherAdjus.Text)
            - Convert.ToDouble(txtDeductions.Text)).ToString(); 
          
     }
        catch (Exception ex ) 
         {
             MessageBox.Show(ex.ToString());
        } 
     }
     
        #endregion

     private void MyEvent(object sender, EventArgs e)
     {
         
         try
         {
             CalculateAll();
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.ToString());
         }
     }
     private void btnSave_Click(object sender, EventArgs e)
     {
         System.Data.SqlClient.SqlConnection sqlcon = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
         System.Data.SqlClient.SqlCommand sqlcmd = new System.Data.SqlClient.SqlCommand();
         string datestr = "1-" + Month + "-" + Year.ToString();
         sqlcmd.CommandText = "select count(*) from payroll where payperiod = ('" + datestr + "') and empid = " + _id;
         sqlcmd.CommandType = CommandType.Text;
         sqlcmd.Connection = sqlcon;
         int count = 0;
         sqlcon.Open();
         count = Convert.ToInt32(sqlcmd.ExecuteScalar());
         sqlcon.Close();

         int insertresult = 0;
         if (count <= 0)
         {
             sqlcmd = new System.Data.SqlClient.SqlCommand("insert into Payroll(empid,payperiod) values(" + _id.ToString() + ",'" + datestr + "')", sqlcon);
             sqlcon.Open();
             insertresult = (int)sqlcmd.ExecuteNonQuery();
             sqlcon.Close();

         }

         sqlcmd = new System.Data.SqlClient.SqlCommand("UpdatePayroll", sqlcon);
         sqlcmd.CommandType = CommandType.StoredProcedure;
         System.Data.SqlClient.SqlParameter sqlparam = new System.Data.SqlClient.SqlParameter("@empID", _id);
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@payperiod", datestr);
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@percent", cbPercentage.Text);
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@clientrate", txtClientRate.Text);
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@actualRate", Convert.ToDouble(txtActualRate.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@paidRate", Convert.ToDouble(txtPaidRate.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@difference", Convert.ToDouble(txtDifference.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@HoursWorkedCurrentMonth", Convert.ToInt32(txtHrsWorkedCurMon.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@HoursPaidWithHold", Convert.ToInt32(txtHrsPaidFromWithHold.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@TotalHoursPaid", Convert.ToDouble(txtTotalHrsPaid.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@CurrentMonthWithHoldAmount", Convert.ToDouble(txtCurMonWithHeldAmount.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@WithHoldBalanceForward", Convert.ToDouble(txtWithHeldBalForw.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@SalaryFromWithHold", Convert.ToDouble(txtSalFromWithHeld.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@PerDiem_otherPayWithHeld", Convert.ToDouble(txtPerDiemWithHeld.Text));

         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@BalanceWithHeldAmount", Convert.ToDouble(txtBalWithHeld.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@FilingFeeDeduction", Convert.ToDouble(txtFilingFeeDeduc.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@OtherAdjustment", Convert.ToDouble(txtOtherAdjus.Text));
         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@Total", Convert.ToDouble(txtTotalPayRoll.Text));

         sqlcmd.Parameters.Add(sqlparam);
         sqlparam = new System.Data.SqlClient.SqlParameter("@RequireWithHodling", (rbRequireWHYes.Checked ? "yes" : "no"));

         sqlcmd.Parameters.Add(sqlparam);
         int success = -1;
         try
         {
             sqlcon.Open();
             success = sqlcmd.ExecuteNonQuery();
             sqlcon.Close();
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.ToString());
         }

         if (success > 0)
             MessageBox.Show("saved successfullly");

     }

     private void expensesToolStripMenuItem_Click(object sender, EventArgs e)
     {
         Expenses objexpenses = new Expenses(this);
         objexpenses.Show();

     }

     private void btnHistory_Click(object sender, EventArgs e)
     {
         BalanceHistory objBalanceHistory = new BalanceHistory(this);
         objBalanceHistory.Show();
     }
     private ToolTip getnewtooltip( )
     { 
         ToolTip tp = new ToolTip();
         tp.ToolTipIcon = ToolTipIcon.Info;
         tp.IsBalloon = true;
         tp.InitialDelay = 1;
         tp.ReshowDelay = 10;
         return tp;
     }
     private void PayRoll_Load(object sender, EventArgs e)
     {
         ToolTip tp = new ToolTip(); ;
         tp= getnewtooltip();
         tp.SetToolTip(txtActualRate, "Client Rate X Percentage");
         
         tp.SetToolTip(txtDifference, "Actual Rate - Paid Rate");
         
         tp.SetToolTip(txtTotalHrsPaid, "Hours Worked Current Month + Hours Paid From With Hold");
        
         tp.SetToolTip(txtCurMonWithHeldAmount, "Difference X Hours Paid From With Hold");
        
         tp.SetToolTip(txtSalFromWithHeld, "Salary From With Held X Paid Rate");
         
         tp.SetToolTip(txtWithHeldBalForw, "Total Balance With Held Amount from previous month");
         
         tp.SetToolTip(txtBalWithHeld, "Current Month With Held Amount + With Held Balance Forward - Salary From With Held - PerDiem Pay");
         
         tp.SetToolTip(txtTotalPayRoll, "total balance with held amount + other adjustments - deductions");
         txtName.Text = _name;
         lblPeriod.Text = "Pay Roll for the period of " + _month + " " + _year.ToString();
        
         GetPayRollData();
         AddToBalanceForward(WithHeldBalanceForward);
        
     }
        
    } 
}
